<template>
  <div class="tutorial-list-page">
    <div class="page-container">
      <!-- 页面标题 -->
    

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <div class="filter-content">
          <!-- 分类筛选 -->
          <div class="category-filter">
            <el-radio-group v-model="queryParams.category" @change="handleFilterChange">
              <el-radio-button :label="undefined">全部</el-radio-button>
              <el-radio-button :label="1">基础入门</el-radio-button>
              <el-radio-button :label="2">进阶技法</el-radio-button>
              <el-radio-button :label="3">高级创作</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 搜索框 -->
          <div class="search-filter">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索教程..."
              @keyup.enter="handleFilterChange"
              @clear="handleFilterChange"
              clearable
            >
              <template #append>
                <el-button @click="handleFilterChange" :icon="Search" />
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="content-section" v-loading="loading">
        <!-- 推荐教程 -->
        <div class="recommend-section" v-if="!queryParams.keyword && !queryParams.category && recommendList.length > 0">
          <div class="section-header">
            <h2><el-icon><Star /></el-icon> 推荐教程</h2>
          </div>
          <div class="recommend-grid">
            <div
              v-for="item in recommendList"
              :key="`recommend-${item.id}`"
              class="recommend-card"
              @click="$router.push(`/tutorial/${item.id}`)"
            >
              <div class="card-image">
                <img 
                  :src="getFullImageUrl(item.coverImage)" 
                  :alt="item.title"
                  @error="(e) => handleImageError(e, 'tutorial')"
                  loading="lazy"
                />
                <div class="recommend-badge">推荐</div>
                <div class="difficulty-badge" :class="`level-${item.difficultyLevel}`">
                  {{ getDifficultyText(item.difficultyLevel) }}
                </div>
              </div>
              <div class="card-content">
                <h3>{{ item.title }}</h3>
                <p>{{ item.summary }}</p>
                <div class="card-info">
                  <div class="info-item">
                    <el-icon><User /></el-icon>
                    <span>{{ item.studyCount }} 人学习</span>
                  </div>
                  <div class="info-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ item.estimatedTime }} 分钟</span>
                  </div>
                </div>
                <div class="card-price">
                  <span v-if="item.isFree" class="free-tag">免费</span>
                  <span v-else class="paid-tag">付费</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 免费教程区域 -->
        <div class="free-section" v-if="!queryParams.keyword && !queryParams.category && freeList.length > 0">
          <div class="section-header">
            <h2><el-icon><Present /></el-icon> 免费教程</h2>
            <router-link to="/tutorial?isFree=true" class="more-link">
              查看更多 <el-icon><ArrowRight /></el-icon>
            </router-link>
          </div>
          <div class="free-grid">
            <div
              v-for="item in freeList"
              :key="`free-${item.id}`"
              class="free-card"
              @click="$router.push(`/tutorial/${item.id}`)"
            >
              <div class="card-image">
                <img 
                  :src="getFullImageUrl(item.coverImage)" 
                  :alt="item.title"
                  @error="(e) => handleImageError(e, 'tutorial')"
                  loading="lazy"
                />
                <div class="free-badge">免费</div>
              </div>
              <div class="card-content">
                <h4>{{ item.title }}</h4>
                <div class="card-stats">
                  <span><el-icon><User /></el-icon> {{ item.studyCount }}</span>
                  <span><el-icon><Clock /></el-icon> {{ item.estimatedTime }}min</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 教程列表 -->
        <div class="tutorial-list">
          <div class="list-header">
            <h2>
              <template v-if="queryParams.category">
                {{ getCategoryText(queryParams.category) }}
              </template>
              <template v-else-if="queryParams.keyword">
                搜索结果
              </template>
              <template v-else>
                全部教程
              </template>
            </h2>
            <span class="total-count">共 {{ total }} 条</span>
          </div>

          <!-- 无数据 -->
          <div class="no-data" v-if="!loading && tutorialList.length === 0">
            <el-empty description="暂无数据">
              <el-button type="primary" @click="clearFilters">清空筛选条件</el-button>
            </el-empty>
          </div>

          <!-- 数据列表 -->
          <div class="tutorial-grid" v-if="tutorialList.length > 0">
            <div
              v-for="item in tutorialList"
              :key="item.id"
              class="tutorial-card"
              @click="$router.push(`/tutorial/${item.id}`)"
            >
              <div class="card-image">
                <img 
                  :src="getFullImageUrl(item.coverImage)" 
                  :alt="item.title"
                  @error="(e) => handleImageError(e, 'tutorial')"
                  loading="lazy"
                />
                <div class="difficulty-badge" :class="`level-${item.difficultyLevel}`">
                  {{ getDifficultyText(item.difficultyLevel) }}
                </div>
                <div class="category-tag">{{ getCategoryText(item.category) }}</div>
                <div class="card-overlay">
                  <div class="overlay-buttons">
                    <el-button
                      :icon="VideoPlay"
                      circle
                      @click.stop="handlePreview(item)"
                      title="预览"
                    />
                    <el-button
                      :icon="StarFilled"
                      circle
                      @click.stop="handleLike(item)"
                      title="点赞"
                    />
                    <el-button
                      :icon="Collection"
                      circle
                      @click.stop="handleFavorite(item)"
                      title="收藏"
                    />
                  </div>
                </div>
              </div>
              <div class="card-content">
                <h3>{{ item.title }}</h3>
                <p>{{ item.summary }}</p>
                <div class="card-details">
                  <div class="detail-item" v-if="item.toolsRequired">
                    <span class="label">工具:</span>
                    <span class="value">{{ item.toolsRequired }}</span>
                  </div>
                  <div class="detail-item" v-if="item.materialsRequired">
                    <span class="label">材料:</span>
                    <span class="value">{{ item.materialsRequired }}</span>
                  </div>
                </div>
                <div class="card-meta">
                  <div class="card-stats">
                    <span><el-icon><User /></el-icon> {{ item.studyCount }}</span>
                    <span><el-icon><Clock /></el-icon> {{ item.estimatedTime }}min</span>
                    <span><el-icon><Document /></el-icon> {{ item.stepsCount }}步</span>
                    <span><el-icon><StarFilled /></el-icon> {{ item.likeCount }}</span>
                  </div>
                  <div class="card-price">
                    <span v-if="item.isFree" class="free-tag">免费</span>
                    <span v-else class="paid-tag">付费</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              v-model:current-page="queryParams.page"
              v-model:page-size="queryParams.size"
              :total="total"
              :page-sizes="[12, 24, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePageChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search, Star, ArrowRight, User, Clock, VideoPlay, Collection, Document, Present, StarFilled
} from '@element-plus/icons-vue'
import { tutorialApi } from '@/api'
import type { Tutorial, TutorialQuery } from '@/types/common'
import { TUTORIAL_CATEGORIES, TUTORIAL_DIFFICULTY } from '@/types/common'
import { getFullImageUrl, handleImageError } from '@/utils/imageUtils'

// 响应式数据
const loading = ref(false)
const tutorialList = ref<Tutorial[]>([])
const recommendList = ref<Tutorial[]>([])
const freeList = ref<Tutorial[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<TutorialQuery>({
  page: 1,
  size: 12,
  keyword: '',
  category: undefined
})

// 获取推荐教程
const fetchRecommendList = async () => {
  try {
    const response = await tutorialApi.getRecommendTutorials(6)
    recommendList.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    recommendList.value = []
  }
}

// 获取免费教程
const fetchFreeList = async () => {
  try {
    const response = await tutorialApi.getFreeTutorials(8)
    freeList.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    freeList.value = []
  }
}

// 获取教程列表
const fetchTutorialList = async () => {
  loading.value = true
  try {
    const response = await tutorialApi.getTutorialPage({
      ...queryParams
    })
    // 确保数据格式正确
    if (response && response.data) {
      tutorialList.value = Array.isArray(response.data.records) ? response.data.records : []
      total.value = response.data.total || 0
    } else {
      tutorialList.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取教程列表失败')
    // 发生错误时重置为空数组
    tutorialList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理筛选变化
const handleFilterChange = () => {
  queryParams.page = 1
  fetchTutorialList()
}

// 处理分页变化
const handlePageChange = () => {
  fetchTutorialList()
}

// 清空筛选条件
const clearFilters = () => {
  queryParams.keyword = ''
  queryParams.category = undefined
  queryParams.page = 1
  fetchTutorialList()
}

// 预览
const handlePreview = (item: Tutorial) => {
  ElMessage.info('预览功能开发中')
}

// 点赞
const handleLike = async (item: Tutorial) => {
  try {
    // TODO: 实现点赞API
    ElMessage.success('点赞成功')
    item.likeCount++
  } catch (error) {
    ElMessage.error('点赞失败，请先登录')
  }
}

// 收藏
const handleFavorite = async (item: Tutorial) => {
  try {
    // TODO: 实现收藏API
    ElMessage.success('收藏成功')
    item.favoriteCount++
  } catch (error) {
    ElMessage.error('收藏失败，请先登录')
  }
}

// 获取分类文本
const getCategoryText = (category: number) => {
  return TUTORIAL_CATEGORIES[category as keyof typeof TUTORIAL_CATEGORIES] || '其他'
}

// 获取难度文本
const getDifficultyText = (level: number) => {
  return TUTORIAL_DIFFICULTY[level as keyof typeof TUTORIAL_DIFFICULTY] || '未知'
}

onMounted(() => {
  fetchRecommendList()
  fetchFreeList()
  fetchTutorialList()
})
</script>

<style scoped>
.tutorial-list-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题 */
.page-header {
  background: #43a047;
  color: #fff;
  border-radius: 12px;
  padding: 40px;
  margin-bottom: 24px;
  text-align: center;
}

.header-content h1 {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 12px;
}

.header-content p {
  font-size: 16px;
  opacity: 0.9;
}

/* 筛选区域 */
.filter-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.category-filter {
  flex: 1;
  min-width: 300px;
}

.search-filter {
  width: 300px;
}

/* 推荐区域 */
.recommend-section,
.free-section {
  margin-bottom: 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.more-link {
  color: #43a047;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.more-link:hover {
  text-decoration: underline;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 24px;
}

.recommend-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.recommend-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.free-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.free-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.free-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 卡片图片 */
.card-image {
  position: relative;
  overflow: hidden;
}

.recommend-card .card-image {
  height: 200px;
}

.free-card .card-image {
  height: 120px;
}

.tutorial-card .card-image {
  height: 180px;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.card-image:hover img {
  transform: scale(1.05);
}

/* 徽章样式 */
.recommend-badge,
.free-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  color: #fff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.recommend-badge {
  background: #43a047;
}

.free-badge {
  background: #2196f3;
}

.difficulty-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: #fff;
}

.difficulty-badge.level-1 {
  background: #4caf50;
}

.difficulty-badge.level-2 {
  background: #ff9800;
}

.difficulty-badge.level-3 {
  background: #f44336;
}

.category-tag {
  position: absolute;
  bottom: 12px;
  left: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 卡片覆盖层 */
.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none; /* 默认不捕获点击事件，让点击穿透到卡片 */
}

.tutorial-card:hover .card-overlay {
  opacity: 1;
  pointer-events: auto; /* hover 时允许点击 overlay 中的按钮 */
}

.overlay-buttons {
  display: flex;
  gap: 8px;
}

.overlay-buttons .el-button {
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: #333;
}

/* 卡片内容 */
.card-content {
  padding: 16px;
}

.recommend-card .card-content {
  padding: 20px;
}

.card-content h3,
.card-content h4 {
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content h3 {
  font-size: 18px;
}

.card-content h4 {
  font-size: 14px;
}

.card-content p {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-info,
.card-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
  margin-bottom: 12px;
}

.info-item,
.card-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-details {
  margin-bottom: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
}

.detail-item .label {
  color: #999;
  min-width: 40px;
}

.detail-item .value {
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-price .free-tag {
  background: #4caf50;
  color: #fff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.card-price .paid-tag {
  background: #ff9800;
  color: #fff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

/* 列表区域 */
.tutorial-list {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.list-header h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 40px;
}

.tutorial-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.tutorial-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.tutorial-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  border-color: #43a047;
}

.pagination-container {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .page-header {
    padding: 24px 20px;
  }

  .header-content h1 {
    font-size: 24px;
  }

  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }

  .category-filter,
  .search-filter {
    width: 100%;
    min-width: auto;
  }

  .recommend-grid {
    grid-template-columns: 1fr;
  }

  .free-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .tutorial-grid {
    grid-template-columns: 1fr;
  }
}
</style>
